/**
 * MySpace(China) Javascript Utility for Reference by UI Team
 * 
 * @author KCZ
 * @version 0.1
 */
 
function domReady(afCallback){
    if (!afCallback){
        return;
    }
    if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", function(){
            afCallback()
        }, false);
    }else{
        (function(){
            try {
                document.documentElement.doScroll("left");
            } catch(error) {
                setTimeout( arguments.callee,0);
                return;
            }
            afCallback();
        })();
    }
}
function json_decode(astr){
    var ljson;
    if(typeof astr == "object"){
        return astr;
    }
    astr = (astr != null) ? astr.split("\n").join("").split("\r").join("") : "";
    if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(astr.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) {
        if (astr != "") {
            ljson = eval('(' + astr + ')');
            return ljson;
        }
    }
    return {};
}
function json_encode(aobj){
    switch (aobj.constructor) {
        case String:
            return '"' + aobj.replace(/(["\\])/g, '\\$1') + '"';
        case Array:
            return '[' + aobj.map(json_encode).join(',') + ']';
        case Object:
            var lxStr = [];
            for (var property in aobj) 
                if (typeof(aobj[property]) != "function") {
                    lxStr.push(json_encode(property) + ':' + json_encode(aobj[property]));
                }
            return '{' + lxStr.join(',') + '}';
        case Number:
            if (isFinite(aobj)) {
                break;
            }
        case Function:
            return '""';
        case Boolean:
            return aobj;
    }
    return String(aobj);	
}
function substitute(template, data, regexp){
  if(!(Object.prototype.toString.call(data) === "[object Array]")){
    data = [data]
  }
  var ret = [];
  for(var i=0,j=data.length;i<j;i++){
    ret.push(replaceAction(data[i]));
  }
  return ret.join("");
  
  function replaceAction(object){
    return template.replace(regexp || (/\\?\{([^}]+)\}/g), function(match, name){
     if (match.charAt(0) == '\\') return match.slice(1);
     return (object[name] != undefined) ? object[name] : '';
    });
  }
}
function getElementsByClassName(asClass, aeP, asTag){
    var lxNew = [];
    asClass = asClass == null ? "" : asClass;
    aeP = aeP == null ? document : aeP;
    asTag = asTag == null ? "*" : asTag;
    
    var lxTag = aeP.getElementsByTagName(asTag);
    var pattern = new RegExp("(^|\s)" + asClass + "(\s|$)");
    for (var i = 0; i < lxTag.length; i++) {
        if ((" " + lxTag[i].className + " ").indexOf(" " + asClass + " ") != -1) {
            lxNew.push(lxTag[i]);
        }
    }
    return lxNew;
}
function ajax(option){
	var xhr = (window.ActiveXObject)?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
    dataEncode();
	try{
        if(option.async !== false){
            option.async = true;
        }
		xhr.open(option.method||"POST",option.url,option.async);
		xhr.setRequestHeader("Content-Type",option.contentType||"application/x-www-form-urlencoded");
		xhr.onreadystatechange = handleStateChange;        
		xhr.send(option.data);
	}catch (ex) {
		return "";
	}
	function handleStateChange(){
		if (xhr!=null&&xhr.readyState==4){
			if(option.callback){
				option.callback(xhr.responseText);
			}
		} 
	}
    function dataEncode(){
      var qs=[];
      if(option.data){
        if(typeof(option.data)=="string"){
          qs.push(option.data);
        }else{
          for(var x in option.data){                                    
            qs.push(x);
            qs.push("=");
            qs.push(option.data[x]);
            qs.push("&");
          }
          qs.pop();
        }
      }
      if(option.method && option.method.toLowerCase()=="get"){
        qs.unshift(option.url.indexOf("?")==-1?"?":"&");
        option.url=option.url + qs.join("");
        option.data = "";
      }else{
        option.data = qs.join("");
      }    
    }
}

function MS_loadAjax(option,path){
  if(navigator.userAgent.indexOf("IE")!=-1){ 
    (function(){ 
      try{ 
        document.documentElement.doScroll("left"); 
        action(); 
      }catch(error) {                                                  
        setTimeout(arguments.callee, 200); 
      }
    })();
  }
  else{ 
    action(); 
  } 
  function action(){
    var xDomain = document.domain.split(".");
    if (xDomain.length >= 2){
      document.domain=xDomain[xDomain.length-2] + "." + xDomain[xDomain.length-1];
    }
    if (!option||!option.url){ 
      return; 
    }
    var liIndex=option.url.indexOf("/",7);
    var lsFrameUrl = option.url.substring(0,liIndex) + (path||"/ajax.html");
    var lsDomin= option.url.substring(7,liIndex).split(".").join("_");
    var lsFrameName = lsDomin + "_frame"; 
    var lsFrameWrapperId = lsDomin+"_frameWrapper"; 
    var leFrameWrapper = document.getElementById(lsFrameWrapperId); 
    if (window.frames[lsFrameName] == null){ 
      leFrameWrapper = document.createElement("span"); 
      leFrameWrapper.id = lsFrameWrapperId; 
      leFrameWrapper.style.display = "none"; 
      document.body.appendChild(leFrameWrapper); 
      leFrameWrapper.innerHTML = '<iframe name='+lsFrameName+'></iframe>'; 
      listen(); 
    }else if(window.frames[lsFrameName].ajax == null){ 
      listen(); 
    }else{ 
      callback(); 
    } 
    function listen(){
      var leIframe =  leFrameWrapper.getElementsByTagName("iframe")[0]; 
      if (navigator.userAgent.indexOf("IE")!=-1) { 
        leIframe.attachEvent("onload", callback); 
      }
      else{
        leIframe.addEventListener("load", callback, false); 
      }
      leIframe.src = lsFrameUrl;                               
    }
    function callback(){
      var lsGUID="_ajax_callback"+Math.floor(Math.random()*16000).toString(16);
      window[lsGUID]=option.callback||function(){};
      option.callback=lsGUID;
      
      var lxUrl=[];
      
      if(option.data){
        if(typeof(option.data)=="string"){
          lxUrl.push(option.data);
        }else{
          for(var x in option.data){					
            lxUrl.push(x);
            lxUrl.push("=");
            lxUrl.push(option.data[x]);
            lxUrl.push("&");
          }
          lxUrl.pop();
        }
      }
      if(option.method && option.method.toLowerCase()=="get"){
        lxUrl.unshift(option.url.indexOf("?")==-1?"?":"&");
        lxUrl.unshift(option.url);
        option.url=lxUrl.join("");
        option.data = "";
      }else{
        option.data = lxUrl.join("");
      }
      window.frames[lsFrameName].ajax(option); 
    }
  }                             
}

function MS_loadJsonP(asUrl, afCallback){
     if (!asUrl) {
        return false;
     }
     var lsUrl = asUrl;
     if (lsUrl.indexOf("callback=") == -1) {
        var lsGUID="_autoCallBack"+Math.floor(Math.random()*16000).toString(16);
        lsUrl = lsUrl + (lsUrl.indexOf("?") != -1 ? "&" : "?") + "callback=" + lsGUID;
     }
     window[lsGUID] = afCallback;
     
     var leTag = document.createElement('script');
     leTag.setAttribute('type', 'text/javascript');
     leTag.setAttribute('src', lsUrl);
     document.getElementsByTagName('head')[0].appendChild(leTag);                                  
}
function insertJSFile(url, callback){
	var node = document.createElement('script');
	node.setAttribute('type', 'text/javascript');		 
	if(callback){				
		if (node.attachEvent){
			node.onreadystatechange = function(){
				if(this.readyState == "loaded" || this.readyState=="complete"){
					callback();
				}
			}
		} else {
			node.onload = callback;
		}
	}
	node.setAttribute('src', url);
	document.getElementsByTagName('head')[0].appendChild(node);   		
} 
function var_dump(args){
	var leNode = document.createElement("div");
	var list = [];
	for(var x in args){
		list.push(x+" : "+args[x]);
	}
	var lsWrapperId = "gip_gip_wrapper";
	var wrapper = document.getElementById(lsWrapperId);
	if(!wrapper){
		wrapper = document.createElement("div");
		wrapper.id = lsWrapperId;
		wrapper.style.cssText = "position:absolute; right:0; top:0; border:1px solid greeen; padding:10px; text-align:center;";
		document.body.insertBefore(wrapper, document.body.firstChild);
	}		
	leNode.innerHTML = "<h1 style='text-align:left;'>"+list.join("<br />")+"</h1>";
	wrapper.insertBefore(leNode, wrapper.firstChild);
}

var K = {
	ajax:function(aoRequest){
		var loXML = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
		try {
			loXML.open(aoRequest.method || "POST", aoRequest.url, false);
			if (aoRequest.contentType){
				loXML.setRequestHeader("Content-Type", aoRequest.contentType);
			}
			loXML.send(aoRequest.data);
		}
		catch (ex) {
			return "";
		}
		if (loXML != null && loXML.readyState == 4) {
			return loXML.responseText;
		}
		return "";
	},
	obj2Query: function(aoOBJ){
		if (aoOBJ == null){
			return null;
		} 
		var lxS = [];
		for (var o in aoOBJ) {
			if (typeof(aoOBJ[o]) == "string" || typeof(aoOBJ[o]) == "number" || typeof(aoOBJ[o]) == "boolean"){
				lxS[lxS.length] = o + "=" + encodeURIComponent(aoOBJ[o]);
			} 	
		}
		return lxS.join("&");
	},
	/*
	 * xDom
	 * */
	hasClass:function(aeTag,asClass){
	    if (!aeTag || !aeTag.className) {
	        return false;
	    }
	    if ((" " + aeTag.className + " ").indexOf(" " + asClass + " ") == -1) {
	        return false;
	    }
	    return true;		
	},
	addClass:function(aeTag, asClass){
	    if (!aeTag) {
	        return false;
	    }		
	    asClass = asClass == null ? 'cnViOver' : asClass;
	    if ((" " + aeTag.className + " ").indexOf(" " + asClass + " ") == -1) {
	        aeTag.className = (aeTag.className + ' ' + asClass).replace(/(^\s*)|(\s*$)/g, "");
	    }
	    return aeTag;
	},
	removeClass:function(aeTag, asClass){
	    if (!aeTag) {
	        return false;
	    }		
	    asClass = asClass == null ? 'cnViOver' : asClass;
	    aeTag.className = aeTag.className.replace(new RegExp('(^|\\s)' + asClass + '(?:\\s|$)'), '$1').replace(/(^\s*)|(\s*$)/g, "");
	},
	addStyle:function(asCss,asId) {
		var lsId = asId || "embedStyle"; 
		var leStyle = asId;
		if(typeof asId == "string"){
			leStyle = document.getElementById(lsId);
		}
		var lbExist = true;
		if(!leStyle){
			leStyle = document.createElement('style');
			leStyle.setAttribute("type", "text/css");
			leStyle.setAttribute("id", lsId);
			lbExist = false;
		} 	
		if (leStyle.styleSheet) { 
			leStyle.styleSheet.cssText=leStyle.innerHTML+asCss;  
		} else {  
			leStyle.appendChild(document.createTextNode(asCss));
		}
		if(!lbExist){
			document.getElementsByTagName("head")[0].appendChild(leStyle);
		}
		return leStyle;
	},	
	getCSSRules:function(aeStyle,asSelector){
		var lxRules = aeStyle.cssRules ? aeStyle.cssRules : aeStyle.rules;
		if(!lxRules){
			return [];
		}else if(typeof asSelector == "number"){
			return [lxRules[asSelector]];
		}else{
			asSelector = asSelector.toLowerCase();
			var lxResult = [];
			for(var i=0;i<lxRules.length; i++){
				if(lxRules[i].selectorText.toLowerCase() == asSelector){
					lxResult.push(lxRules[i]);
				}
			}		
			return lxResult;
		}
	},
	insertCSSRule:function(aeStyle,asSelector, asText, aiIndex){
		if(!aiIndex){
			var lxRules = aeStyle.cssRules ? aeStyle.cssRules : aeStyle.rules;
			aiIndex = lxRules.length;
		}
		if(aeStyle.inertRule){
			aeStyle.inertRule(asSelector + "{" + asText + "}", aiIndex);
		}else if(aeStyle.addRule){
			aeStyle.addRule(asSelector, asText, aiIndex);
		}
	},
	deleteCSSRule:function(aeStyle,asSelector){
		var lxIndex = [];
		var lxRules = aeStyle.cssRules ? aeStyle.cssRules : aeStyle.rules;
		if(asSelector == null){
			lxIndex.push(lxRules.length - 1);
		}else if(typeof asSelector == "string"){
			asSelector = asSelector.toLowerCase();		
			for(var i = 0; i<lxRules.length; i++){
				if(lxRules[i].selectorText.toLowerCase() == asSelector){
					lxIndex.push(i);	
				}
			}
		}else if(typeof asSelector == "number"){
			lxIndex.push(asSelector);		
		}
		for(var j = lxIndex.length - 1; j>=0; j--){
			var liIndex = lxIndex[j];
			if(aeStyle.deleteRule){
				aeStyle.deleteRule(liIndex);
			}else if(aeStyle.removeRule){		
				aeStyle.removeRule(liIndex);
			}
		}
	},	
	getEvent:function(afEvent){
		if(!afEvent){
			return null;
		}
		if(window.event){
			return window.event;
		}
		var lfEvent = afEvent.caller;
		while(lfEvent != null){
			var loEvent = lfEvent.arguments[0];
			if(loEvent && loEvent.constructor == MouseEvent){
				return loEvent;
			}
			lfEvent = lfEvent.caller;
		}
		return null;
	},
	addEvent:function(aeTag, asEvt, afHandler, abCapture){
        abCapture=abCapture||false;
        asName = asName.toLowerCase();
        if(typeof aeNode.addEventListener != 'undefined'){
                if(asName === 'mouseenter'){
                        aeNode.addEventListener('mouseover', mouseEnter(afHandler), abCapture);
                }else if(asName === 'mouseleave'){
                        aeNode.addEventListener('mouseout', mouseEnter(afHandler), abCapture);
                }else{
                        aeNode.addEventListener(asName, afHandler, abCapture);
                }
        }else if(typeof aeNode.attachEvent != 'undefined'){
                aeNode.attachEvent('on' + asName, afHandler);
        }else{
                aeNode['on' + asName] = afHandler;
        }
        function mouseEnter(afHandler){
          return function(event){
                  var eTarget = event.relatedTarget;
                  if (this === eTarget || isAChildOf(this, eTarget)){ 
                          return; 
                  }
                  afHandler.call(this, event);
          }
        }
        function isAChildOf(eParent, eChild){
          if(eParent === eChild) { 
                  return false; 
          }
          while (eChild && eChild !== eParent){ 
                  eChild = eChild.parentNode; 
          }
          return eChild === eParent;
        }
	},
	removeEvent:function(aeTag,asEvt,afHandler){
	    if(!aeTag){
	        return false;
	    }
	    if(navigator.userAgent.indexOf("IE")!=-1){
	        aeTag.detachEvent("on"+asEvt,afHandler);
	    }else{       
	        aeTag.removeEventListener(asEvt,afHandler,false);
	    }
	},
	stopBubble:function(event) {
	    event = window.event || event;
	    if(event.stopPropagation) {
	        event.stopPropagation();
	    } else {
	        event.cancelBubble = true;
	    }
	},
	preventDefault:function(event) {
	    event = window.event || event;
	    if(event.preventDefault) {
	        event.preventDefault();
	    } else {
	        event.returnValue = false;
	    }
	},
	/*
	 * xPage
	 * */
	 /**
	  * Finding the Current Position of the Mouse Cursor Within the Entire Web Page
	  */
	getMouse:function(event){
		event = event || windiow.event;
		var isIE = navigator.userAgent.indexOf("IE")!=-1;
		return {
			x: isIE ? event.clientX + document.documentElement.scrollLeft : event.pageX,
			y: isIE ? event.clientY + document.documentElement.scrollTop : event.pageY
		};
	},
	 /**
	  * Testing!!!
	  * Retreiving the Position of the Mouse Relative to the Current Element
	  */
	getMouseInElement:function(event){
		return {
			x: (event && event.layerX) || window.event.offsetX,
			y: (event && event.layerY) || window.event.offsetY
		};
	},
	pageX:function (aeTag){
		return aeTag.offsetParent? aeTag.offsetLeft + this.pageX(aeTag.offsetParent): aeTag.offsetLeft;
	},
	pageY:function (aeTag){
		return aeTag.offsetParent? aeTag.offsetTop + this.pageY(aeTag.offsetParent): aeTag.offsetTop;
	},
	scrollToThis:function(aeNode,aiDiff){
		var leNode = document.getElementById(aeNode);
		var liDiff = aiDiff || 250;
		function pageX(aeTag){
			return aeTag.offsetParent? aeTag.offsetLeft + pageX(aeTag.offsetParent): aeTag.offsetLeft;
		}
		function pageY(aeTag){
		
			return aeTag.offsetParent? aeTag.offsetTop + pageY(aeTag.offsetParent): aeTag.offsetTop;
		}
		window.scrollTo(pageX(leNode),pageY(leNode)-liDiff);
	},	
	 /**
	  * Deternming the Length and the Width of the Current Web Page
	  */
	getPageSize:function(){
		var lsObj;		
		if(navigator.userAgent.indexOf("IE")!=-1){
			lsObj = "documentElement";
		}else{
			lsObj = "body";
		}
		return{
			x: document[lsObj].scrollWidth,
			y: document[lsObj].scrollHeight
		};
	},
	 /**
	  * Deternming How Far the Browser Is Scrolled
	  * the first part is for IE, and other browsers will return 0
	  */
	getScroll:function(){
		if(navigator.userAgent.indexOf("IE")!=-1){
			return{
				x: document.documentElement.scrollLeft || document.body.scrollLeft,
				y: document.documentElement.scrollTop || document.body.scrollTop
			};
		}else{
			return{
				x: self.pageXOffset,
				y: self.pageYOffset
			};
		}	
	},
	 /**
	  * Deternming the Height and Width of the Browser Viewport
	  * document.bodyElement.clientWidth will return right value in IE, while Firefox will return the width of the whole page 
	  */
	getViewPort:function(){
		/**
		var lsObj;		
		if(navigator.userAgent.indexOf("IE")!=-1){
			lsObj = "documentElement";			
		}else{
			lsObj = "body";
		}
		return{
			x: document[lsObj].clientWidth,
			y: document[lsObj].clientHeight
		};
		 */
		if(navigator.userAgent.indexOf("IE")!=-1){
			return{
				x: document.documentElement.clientWidth || document.body.clientWidth,
				y: document.documentElement.clientHeight || document.body.clientHeight
			};
		}else{
			return{
				x: self.innerWidth,
				y: self.innerHeight
			};
		}		 
		
	},
	/**
	 * Maximize Window
	 */
	maxWindow:function(){
		self.moveTo(0,0);
		self.resizeTo(screen.availWidth,screen.availHeight);
	},
	getTarget:function(event){
	    event = event || window.event;
	    return event.target || event.srcElement;
	},
	setOpacity:function(aeNode,aiLevel){
		if(anavigator.userAgent.indexOf("IE")!=-1){
			aeNode.style.filter = 'alpha(opacity=' + aiLevel + ')';
		}else{
			aeNode.style.opacity = aiLevel / 100;
		}
	},
	getParameter:function(asName){
	    var reg = new RegExp("(^|&|\\?|\\s)"+ asName +"\\s*=\\s*([^&]*?)(\\s|&|$)", "i");
	    if (reg.test(document.location.search)){
	    	 return RegExp.$2.replace(/[\x0f]/g, ";");
	    }
	    return "";
	},
	getParameter2:function(asName){
		var loQuery = {};
	    var lsSearch = location.search.split("?")[1];
	    var lxPair = lsSearch.split("&");
	    for(var i=0; i<lxPair.length; i++) {
	    	var lxQuery = lxPair[i].split("=");
	    	if(lxQuery.length > 1){
	    		loQuery[lxQuery[0]] = lxQuery[1];
	    	}
	    	if(i == lxPair.length -1){
	    		loQuery[lxQuery[0]] = lxQuery[1].split("#")[0];
	    	}
	    }
	    return loQuery[asName];
	},	
	totalLength:function(asStr){
	    var liLength=0;
	    if(asStr!=""){
	        for(var i=0;i<asStr.length;i++){ 
	            var code=escape(asStr.charAt(i)); 
	            if((code.length>=4)&&(code<'%uFF60'||code>'%uFF9F')){ 
	                liLength+=2; 
	            }else{
	                liLength++; 
	            }
			} 
	    }
	    return liLength; 
	},
	trim:function(asStr){
	    asStr = asStr == null ? "" : asStr;
	    return asStr.replace(/(^\s*)|(\s*$)/g, "");
	},
	getStyle:function(aeNode,asName){
	    if (typeof(aeNode)=="string"){
			 aeNode=document.getElementById(aeNode);
		}
		var lsIE,lsW3C;
		if(asName.indexOf("-")!=-1){
			lsW3C = asName;
			// to be improved
	        lsIE = asName.split("-")[0]+asName.split("-")[1].charAt(0).toUpperCase()+asName.split("-")[1].substring(1);
		}else{
			lsIE = asName;
	        lsW3C = asName.replace(/([A-Z])/g, "-$1");
		}
	    return navigator.userAgent.indexOf("IE")!=-1 ?aeNode.currentStyle[lsIE]:document.defaultView.getComputedStyle(aeNode, "").getPropertyValue(lsW3C);
	},	
	smartView:function(asHTML, axData){
	    var lxLeft = asHTML.split("{K:");
	    var lxHTML = [];
	    if(!axData){
	    	return false;
	    }
		if(axData.constructor != Array){
			if(axData.constructor == Number){
				var liIndex = axData;
				axData = [];				
				axData[liIndex - 1] = {};
			}else{
				axData = [axData];	
			}
		}
	    for (var i = 0; axData && i < axData.length; i++) {
	        for (var j = 0; j < lxLeft.length; j++) {
	            var lsProp = lxLeft[j].substring(0, lxLeft[j].indexOf("}"));
	            if (lsProp != "") {
	            	if(lsProp == "k"){            		
	            		lxHTML[lxHTML.length] = i;
	                	lxHTML[lxHTML.length] = lxLeft[j].substring(lxLeft[j].indexOf("}") + 1);
	            	}else{
	            		lxHTML[lxHTML.length] = axData[i][lsProp];
	                	lxHTML[lxHTML.length] = lxLeft[j].substring(lxLeft[j].indexOf("}") + 1);
	            	}
	               
	            }
	            else {
	                lxHTML[lxHTML.length] = lxLeft[j];
	            }
	        }
	    }
	    return lxHTML.join("");
	},
	copyToClipboard:function(asTxt) {   
		if(window.clipboardData) {   
			window.clipboardData.clearData();   
			window.clipboardData.setData("Text", asTxt);
			return true;
		} else if(navigator.userAgent.indexOf("Opera") != -1) {   
			window.location = asTxt;
			return true;
		} else if (window.netscape) {   
			try {   
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");   
			} catch (e) {   
	   			alert("被浏览器拒绝！\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'"); 
				return false;
			}   
			var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);   
			if (!clip){
				return false;
			}   
				   
			var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);   
			if (!trans){
				return false;
			}   
				   
			trans.addDataFlavor('text/unicode');   
			var str = {};   
			var len = {};   
			var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);   
			var copytext = asTxt;   
			str.data = copytext;   
			trans.setTransferData("text/unicode",str,copytext.length*2);   
			var clipid = Components.interfaces.nsIClipboard;
			if (!clip){
				return false;
			}
			clip.setData(trans,null,clipid.kGlobalClipboard);
			return true;
		}   
	},
	imageSize:function(axImg,axWidth,aiHeight){
		if(axImg==null||axWidth==null) return;
		var lxImg;
		if(axImg.nodeType){
			lxImg = [axImg];
		}else{
			lxImg = axImg;
		}
		for(var i=0;i<lxImg.length;i++){
			var leImage = lxImg[i];
			var loImage = new Image();
			loImage.onload = action(leImage);
			loImage.src = leImage.src;
		}
		function action(aeNode){
			return function(){
				if(axWidth.length==1){
					var liWidth=axWidth[0];
					if(aeNode.width>liWidth){
						aeNode.style.height=Math.ceil(aeNode.height * liWidth/aeNode.width)+"px";
						aeNode.style.width=liWidth+"px";
					}
				}else if(axWidth.length==2){
					var liWidth;
					var liWidth0=axWidth[0];
					var liWidth1=axWidth[1];
					if(aeNode.width>liWidth1){
						liWidth=liWidth1;
					}else if(aeNode.width<aeNode.height&&aeNode.width>liWidth0){
						liWidth=liWidth1;
					}
					aeNode.style.height=Math.ceil(aeNode.height * liWidth/aeNode.width)+"px";
					aeNode.style.width=liWidth+"px";
				}
				if(aiHeight!=null){
					if(aeNode.height>aiHeight){
						aeNode.style.width=Math.ceil(aeNode.width * aiHeight/aeNode.height)+"px";
						aeNode.style.height=aiHeight+"px";
					}
				}		
			}
		}
	},
	//testing
	browser:function(){
		var userAgent = navigator.userAgent.toLowerCase();		
		return {
			version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
			safari: /webkit/.test( userAgent ),
			opera: /opera/.test( userAgent ),
			msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
			mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
		};	
	},	
	/**
	 * @author KCZ
	 * @version 0.2
	 * 
	 * @param {Object} aeNode, dom node with animation
	 * @param {Object} asStyle, style property name,(e.g., marginLeft)
	 * @param {Object} aoOption
	 * 					{startVal: start value, default:0
	 * 					 endVal: end value, default: the exact value of the node style property
	 * 					 interval: interval time finishing animation, unit:milli-second, default: 1000
	 * 					}
	 * @method go, begin to show animation
	 * @method onEnd, the method is invoked at the end of the animation	 
	 */
	animation : function(aeNode,asStyle,aoOption){
		var obj = {}; 
		if(aeNode ==  null){return false;}
		if(aoOption == null){aoOption = {};}
		var lsPropName = asStyle || "width";
		var UNIT = 5;
		
		obj.node = aeNode;
		obj.style = asStyle || "width";		
		obj.startVal = aoOption.from || 0;
		// get default style property value of the node
		obj.endVal = aoOption.to || parseInt(navigator.userAgent.indexOf("IE")!=-1 ?aeNode.currentStyle[obj.style]:document.defaultView.getComputedStyle(aeNode, "").getPropertyValue(obj.style.replace(/([A-Z])/g, "-$1")));
		obj.interval = aoOption.interval || 1000;
		var liInterval;	
		obj.go = function(){
			if(obj.doing){return false;}
			liInterval = obj.interval / UNIT;
			obj.doing = true;
			for (var i = 0; i <= liInterval; i += UNIT) {repeater(i);}
		};
	
		function repeater(index){
			(function(){setTimeout(function(){
				aeNode.style[lsPropName] = (obj.startVal + Math.round((index / liInterval) * (obj.endVal - obj.startVal))) + "px";
				if(index == liInterval){
					aeNode.style[lsPropName] = obj.endVal;
					obj.doing = false;
					if(obj.onEnd){obj.onEnd();}
				}
			}, (index + 1) * UNIT);})();
		}
		return obj;
	}	
}

function getOffsetX(aeNode){
	if(!aeNode){
		return false;
	}
	return aeNode.offsetParent ? aeNode.offsetLeft + getOffsetX(aeNode.offsetParent) : aeNode.offsetLeft;
}

function getOffsetY(aeNode){
	if(!aeNode){
		return false;
	}
	return aeNode.offsetParent ? aeNode.offsetTop + getOffsetY(aeNode.offsetParent) : aeNode.offsetTop;
}


var KK = {
	/**
	 * 
	 * @param {Object} aeNode
	 * 
	 * @inherit K.getStyle
	 * 			K.getScroll
	 * 			K.getViewPort
	 */
	goCenter: function(aeNode){
		var leNode;
		if(typeof aeNode == "string"){
			leNode = document.getElementById(aeNode);
		}
		var lsPosition = K.getStyle(leNode,"position");
		var liWidthNode = parseInt(K.getStyle(leNode,"width"));
		var liHeightNode = parseInt(K.getStyle(leNode,"height"));

		leNode.style.position = "absolute";
		leNode.style.marginTop = "0px";
		leNode.style.marginLeft = "0px";
		leNode.style.left = Math.floor((K.getViewPort().x - liWidthNode) / 2)+K.getScroll().x + "px";
		leNode.style.top = Math.floor((K.getViewPort().y - liHeightNode) / 2)+K.getScroll().y + "px";
		
		K.addEvent(window,"resize",function(){KK.goCenter(aeNode);});
		K.addEvent(window,"scroll",function(){KK.goCenter(aeNode);});		
	}	
}

function cssQuery(selector, root){
	if(!selector){
		return [null];
	}	
    root = root == null ? document : root;
    root = typeof root == "string" ? document.getElementById("root") : root;
    // Attempt to fail gracefully in lesser browsers
    if (!document.getElementsByTagName) {
        return new Array();
    }
    // Split selector in to tokens
    var tokens = selector.split(' ');
    var currentContext = [root];
    for (var i = 0; i < tokens.length; i++) {
        token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, '');
        if (token.indexOf('.') > -1) {
            // Token contains a class selector
            var bits = token.split('.');
            var tagName = bits[0];
            var className = bits[1];
            if (!tagName) {
                tagName = '*';
            }
            // Get elements matching tag, filter them for class selector
            var found = new Array;
            var foundCount = 0;
            for (var h = 0; h < currentContext.length; h++) {
                var elements;
                if (tagName == '*') {
                    var leNode = currentContext[h];
                    elements = leNode.all ? leNode.all : leNode.getElementsByTagName('*');
                } else {
                    elements = currentContext[h].getElementsByTagName(tagName);
                }
                for (var j = 0; j < elements.length; j++) {
                    found[foundCount++] = elements[j];
                }
            }
            currentContext = new Array;
            var currentContextIndex = 0;
            for (var k = 0; k < found.length; k++) {
                if (found[k].className && found[k].className.match(new RegExp('\\b' + className + '\\b'))) {
                    currentContext[currentContextIndex++] = found[k];
                }
            }
            continue; // Skip to next token
        }
        
        if (token.indexOf('#') > -1) {
            // Token is an ID selector
            var bits = token.split('#');
            var tagName = bits[0];
            var id = bits[1];
            var element = document.getElementById(id);
            if (tagName && element.nodeName.toLowerCase() != tagName) {
                // tag with that ID not found, return false
                return new Array();
            }
            // Set currentContext to contain just this element
            currentContext = new Array(element);
            continue; // Skip to next token
        }
        
        // Code to deal with attribute selectors
        if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
            var tagName = RegExp.$1;
            var attrName = RegExp.$2;
            var attrOperator = RegExp.$3;
            var attrValue = RegExp.$4;
            if (!tagName) {
                tagName = '*';
            }
            // Grab all of the tagName elements within current context
            var found = new Array;
            var foundCount = 0;
            for (var h = 0; h < currentContext.length; h++) {
                var elements;
                if (tagName == '*') {
                    elements = getAllChildren(currentContext[h]);
                } else {
                    elements = currentContext[h].getElementsByTagName(tagName);
                }
                for (var j = 0; j < elements.length; j++) {
                    found[foundCount++] = elements[j];
                }
            }
            currentContext = new Array;
            var currentContextIndex = 0;
            var checkFunction; // This function will be used to filter the elements
            switch (attrOperator) {
                case '=': // Equality
                    checkFunction = function(e){
                        return (e.getAttribute(attrName) == attrValue);
                    };
                    break;
                case '~': // Match one of space seperated words 
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).match(new RegExp('\\b' + attrValue + '\\b')));
                    };
                    break;
                case '|': // Match start with value followed by optional hyphen
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).match(new RegExp('^' + attrValue + '-?')));
                    };
                    break;
                case '^': // Match starts with value
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).indexOf(attrValue) == 0);
                    };
                    break;
                case '$': // Match ends with value - fails with "Warning" in Opera 7
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length);
                    };
                    break;
                case '*': // Match ends with value
                    checkFunction = function(e){
                        return (e.getAttribute(attrName).indexOf(attrValue) > -1);
                    };
                    break;
                default:
                    // Just test for existence of attribute
                    checkFunction = function(e){
                        return e.getAttribute(attrName);
                    };
            }
            currentContext = new Array;
            var currentContextIndex = 0;
            for (var k = 0; k < found.length; k++) {
                if (checkFunction(found[k])) {
                    currentContext[currentContextIndex++] = found[k];
                }
            }
            // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
            continue; // Skip to next token
        }
        
        // If we get here, token is JUST an element (not a class or ID selector)
        tagName = token;
        var found = new Array;
        var foundCount = 0;
        for (var h = 0; h < currentContext.length; h++) {
            var elements = currentContext[h].getElementsByTagName(tagName);
            for (var j = 0; j < elements.length; j++) {
                found[foundCount++] = elements[j];
            }
        }
        currentContext = found;
    }
    return currentContext;
}


function checkInput(){
	var obj = {};	
	
	//check  text input is null or not
	//checkInputChoice(byClass("required",document, "input"));
	obj.isNull = function(axInputText){		
		var lxInputText = axInputText;
		for(var i=0; i<lxInputText.length; i++){
			var leInputText = lxInputText[i];
			if(trim(leInputText.value) == ""){
				if(obj.nullError){
					obj.nullError(leInputText);
				}
				return false;
			}
		}
		return true;
	}
	//
	//checkInputChoice(byClass(lsWrapperClass));
	obj.checkChoice = function(axInputWrapper){
		var liMax = Math.INFINITY;
		var lxInputWrapper = axInputWrapper;
		
		for(var i=0; i<lxInputWrapper.length; i++){
			var leInputWrapper = lxInputWrapper[i];
			var liTotalChecked = getTotalChecked(leInputWrapper);
			if(leInputWrapper.getAttribute("max") != ""){
				liMax = parseInt(leInputWrapper.getAttribute("max"));
			}else{
				liMax = Math.INFINITY;
			}
			if(liTotalChecked > liMax){			
				return false;
			}else if(liTotalChecked == 0){
				if(obj.nullError){
					obj.nullError(leInputWrapper);
				}			
				return false;			
			}
		}
		return true;		
	}
	
	// keep checked checkbox below maximum 
	obj.listenCheckbox = function(axInputWrapper){
		for(var i=0; i<axInputWrapper.length; i++){
			var leInputWrapper = axInputWrapper[i];
			var lxInput = leInputWrapper.getElementsByTagName("input");
			var liMax = Math.INFINITY;
			if(leInputWrapper.getAttribute("max") != null){
				liMax = parseInt(leInputWrapper.getAttribute("max"));
			}
		
			for(var j=0; j<lxInput.length; j++){
				var leNode = lxInput[j];
				if(leNode.type == "checkbox"){
					addEvent(leNode,"click",clickCheckboxHandler(leInputWrapper,liMax));	
				}
			}
			
		}		
		function clickCheckboxHandler(aeNode,aiMax){
			return function(){
				var lxInput = aeNode.getElementsByTagName("input");
				var liChecked = getTotalChecked(aeNode);
				if(liChecked >= aiMax){
					for(var i=0;i<lxInput.length;i++){
						var leInput = lxInput[i];
						if(leInput.type == "checkbox" && leInput.checked == false){
							leInput.disabled = true;
						}
					}
				}else{
					for(var i=0;i<lxInput.length;i++){
						var leInput = lxInput[i];
						if(leInput.checked == false){
							leInput.disabled = false;
						}
					}
				}
				
			}	
		}		
	}
	return obj;
	
	function getTotalChecked(aeNode){
		if(!aeNode){
			return -1;
		}
		var lxInput = aeNode.getElementsByTagName("input");
		var cnt = 0;
		for(var i=0; i<lxInput.length; i++){
			var leNode = lxInput[i];
			if((leNode.type == "radio" || leNode.type == "checkbox") && leNode.checked){
				cnt++;
			}
		}
		return cnt;	
	}
	function addEvent(aeTag, asEvt, afHandler){
	    if (!aeTag) {
	        return false;
	    }if (navigator.userAgent.indexOf("IE") != -1) {
	        aeTag.attachEvent("on" + asEvt, afHandler);
	    } else {
	        aeTag.addEventListener(asEvt, afHandler, false);
	    }
	}	
	function trim(asStr){
	    asStr = asStr == null ? "" : asStr;
	    return asStr.replace(/(^\s*)|(\s*$)/g, "");
	}	
}

//此方法依赖于addEvent extended with mouseenter and mouseleave
function hoverStyle(asLayerId,asLabelId,aiInterval){
	aiInterval=aiInterval||0;
	var timer=null;
	var eLayer=document.getElementById(asLayerId);
	var eLabel=document.getElementById(asLabelId);
	if(!eLayer||!eLabel){
		return false;
	}
	listen();
	
	function listen(){
		addEvent(eLabel,'mouseenter',enterHandler);
		addEvent(eLabel,'mouseleave',leaveHandler);
		addEvent(eLayer,'mouseenter',enterHandler);
		addEvent(eLayer,'mouseleave',leaveHandler);
	}
	function enterHandler(){
		clearTimeout(timer);
		eLayer.style.display="block";
	}
	function leaveHandler(){
		timer=setTimeout(function(){
			eLayer.style.display="none";
		},aiInterval);
	}
}
/*---------------------Testing-------------------------------*/

function includeUrl(asUrl, afCallback, asType){
	if (asUrl == null) {
		return false;
	}
	var leHead = document.getElementsByTagName('head')[0];
	if (asType == null){
		asType = "js";
	}				
	var leTag = null;
	if (asType == "js") {
		leTag = document.createElement('script');
		leTag.setAttribute('type', 'text/javascript');
		leTag.setAttribute('src', asUrl);
	}
	else {
		leTag = document.createElement('link');
		leTag.setAttribute('rel', 'stylesheet');
		leTag.setAttribute('type', 'text/css');
		leTag.setAttribute('href', asUrl);
	}
	if (afCallback != null) {
		leTag.onload = leTag.onreadystatechange = function(){
			if (leTag.ready) {
				return false;
			}
			if (!leTag.readyState || leTag.readyState == "loaded" || leTag.readyState == 'complete') {
				leTag.ready = true;
				afCallback(asUrl);
			}
		};
	}
	leHead.appendChild(leTag);
	return true;
}


/**
 * 
 * @param {String} asForm	Form的ID或引用
 * @param {Function} afCallback	回调函数的名字，有一个参数，即为返回的数据对象
 * @param {String} asMethod	Form提交的方法，默认为get
 */

function xForm(asForm,afCallback,asMethod){
	asMethod = asMethod.toLowerCase() || "get";
	var leForm = typeof asForm == "string"?document.getElementById(asForm):asForm;
	var lsUrl = leForm.getAttribute("action");
	if(asMethod == "get"){
		CNMS.loadJsonP(lsUrl,afCallback);
	}else{
		var loRequest = {
			"webservices":lsUrl,
			"values":encodeURIComponent(getFormQueryString(leForm)),
			"contentType":"application/x-www-form-urlencoded"
		}
		CNMS.loadAjax(loRequest,afCallback);
	}
	return false;
}

function getFormQueryString(asForm){
	var leForm = typeof asForm == "string"?document.getElementById(asForm):asForm;
	var lxQueryNode = [];
	var lxQueryString = [];
	var lxInput = leForm.getElementsByTagName("input");
	var lxTextArea = leForm.getElementsByTagName("textarea");
	var lxSelect = leForm.getElementsByTagName("select");
	appendNodeList(lxInput);
	appendNodeList(lxTextArea);
	appendNodeList(lxSelect);

	
	for(var i=0; i<lxQueryNode.length; i++){
		var leNode = lxQueryNode[i];
		if(leNode.name != ""){
			lxQueryString.push(leNode.name);
			lxQueryString.push("=");
			lxQueryString.push(leNode.value);
			lxQueryString.push(",");					
		}
	}
	lxQueryString.pop();
	return lxQueryString.join("");
	
	function appendNodeList(axNodeList){
		for(var i=0; axNodeList && i<axNodeList.length; i++){
			lxQueryNode.push(axNodeList[i]);
		}
	}
}

//var xmlDoc = XmlLoad(xml);
//xmlDoc.getElementsByTagName("node")[0].getElementsByTagName("link")[0].childNodes[0].nodeValue;
function XmlLoad(XmlText) {
	var xmlDoc;
	try{
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async=false;
			xmlDoc.loadXML(XmlText);    
	}catch(e){
			try{
					xmlDoc=document.implementation.createDocument("","",null);
					parser=new DOMParser();
					var xmlDoc = parser.parseFromString(XmlText,"text/xml")

			}catch(e){}
	}
	return xmlDoc;  
}



function postIframe(args, actionUrl){
		var wrapperId = "_gip_post_count_wrapper";
		var wrapper = document.createElement('div');
		wrapper.style.display = "none";
		document.body.appendChild(wrapper);
		
		var options = [];
		for(var x in args){
			options.push('<input type="hidden" name="'+x+'" value="'+args[x]+'" />');
		}
		var iframeName = "_gip_post_target_" + new Date().getTime();
		var html = '<iframe name="'+iframeName+'"></iframe><form target="'+iframeName+'" action="'+actionUrl+'" method="post">'+options.join("")+'</form>'
		wrapper.innerHTML = html;
		wrapper.getElementsByTagName('form')[0].submit();
}
//设置textarea光标位置
function setCursorPosition(node, pos){  
	if(node.setSelectionRange){
		node.focus();
		node.setSelectionRange(pos,pos);
	}else if (node.createTextRange) {
		var range = node.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}


		
//获取textarea光标位置
function getCursorPosition(node){        
	var curPos = 0;	
	// IE Support
	if (document.selection) {
		node.focus ();
		var sel = document.selection.createRange ();
		sel.moveStart ('character', -node.value.length);
		curPos = sel.text.length;
	}
	// Firefox support
	else if (node.selectionStart || node.selectionStart == '0'){
		curPos = node.selectionStart;
	}
	return curPos;
}



function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	if(!expiredays) expiredays = 30;
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}


function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){ 
			c_start=c_start + c_name.length+1 ;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}